import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Navigator, Image, Picker, Button} from '@tarojs/components';
import {AtIcon, AtModal, AtModalAction, AtModalContent, AtModalHeader} from 'taro-ui';
import {http} from '../../utils/http';
import {
  IDENTITY,
  RESOURCE_URL,
  SUPPLIER_WITHDRAW,
  WITHDRAW
} from '../../constants/api';
import {user} from '../../utils/user.service'
import {platform} from "../../utils/platform-settting.service";
import {GetRequest, vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";
import './wallet.scss';
import './supplier.scss';

type PageState = {
  distributors: string
  supplierIndex: number
  supplierList: any
  wallet: any
  withdraw: number
  showWithdraw: boolean
  submitting: boolean
  uuid: string
  isSeller: boolean
  payMethod: number
  dataColor: any
  formData: object
}

export default class Wallet extends Component {
  state: PageState = {
    distributors: '',
    supplierIndex: 0,
    supplierList: [],
    wallet: {
      accNm: '',
      acctNo: '',
      balance: 0,
      bankName: '',
      fee: '',
      maxAmount: '',
      minAmount: '',
      phone: '',
    },
    isSeller: false,
    withdraw: 0,
    showWithdraw: false,
    submitting: false,
    uuid: '',
    payMethod: 0,
    formData: {
      supplier_id: '104',
      s: 10,
      p: 1
    },
  }

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    // 获取供应商
    const res = await http.HGet(IDENTITY);
    // const supplierList = res.data.superCheckerList;
    const supplierList = res.data.SupplierList;
    this.setState({
      supplierList
    }, () => {
      this.onChange({
        detail: {
          value: this.state.supplierIndex
        }
      });
    });

    this.setState({
      uuid: Taro.getCurrentInstance().router.params.uuid,
      isSeller: Taro.getCurrentInstance().router.params.isSeller,
      payMethod: platform.info.payMethod
    })
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
  }

  inputChange(value) {
    this.setState({withdraw: Number(value.detail.value)})
  }

  disUse() {
    Taro.showToast({
      title: '请先完成认证！',
      icon: 'none'
    })
  }

  async getData() {
    const {pageStatus}: any = this.state;
    if (pageStatus == false) return;
    Taro.showLoading({title: '加载中...'});
    const wallet = await http.HGet(SUPPLIER_WITHDRAW, {supplierId: this.state.formData.supplier_id})
    Taro.hideLoading();
    if (wallet) {
      this.setState({wallet})
    } else {
      this.setState({
        wallet: {
          accNm: '',
          acctNo: '',
          balance: 0,
          bankName: '',
          fee: '',
          maxAmount: '',
          minAmount: '',
          phone: '',
        }
      })
    }
  }

  async cashOut() {
    const ret = await http.postCondition(WITHDRAW, {
      amount: this.state.wallet.balance,
      supplierId: this.state.formData.supplier_id,
      isAll: 1
    })
    if (ret) {
      this.setState({showWithdraw: true})
    }

  }

  stop(e) {
    e.stopPropagation()
  }

  closedWithDraw() {
    this.setState({showWithdraw: false}, () => {
      this.getData();
    });
  }

  // 提示框点击遮罩层
  confirmClose(isShow = false) {
    this.setState({
      confirmShow: isShow
    });
  }

  // 提示框点击遮罩层
  confirmOpen(id) {
    if (id) {
      this.setState({
        keyId: id
      }, async () => {
        console.log(this.state.keyId)
      })
    }
    this.setState({
      confirmShow: true
    });
  }

  onChange(e) {
    const {supplierList, formData}: any = this.state;
    const supplierIndex = Number(e.detail.value);
    const distributors = supplierList[supplierIndex].company;
    formData.supplier_id = supplierList[supplierIndex].supplier_id;
    this.setState({
      supplierIndex,
      distributors,
      formData
    }, () => {
      this.getData();
    });
  }
  getHistoryLength(){
    return window.history.length > 0
  }
  render() {
    const {wallet, showWithdraw, distributors, supplierIndex, supplierList, formData} = this.state
    const dataColor: any = Taro.getStorageSync('colorData');
    return (
      <View className='wallet-root'>
        <GzhAuth />
        <Index />
        <View className='cancel-after-management-distributors'>
          <View className='cancel-after-management-distributors-text'>
            供应商：{distributors}
          </View>
          <Picker
            value={supplierIndex}
            range={supplierList}
            rangeKey='company'
            onChange={this.onChange.bind(this)}
            mode='selector'
          >
            <View
              className='cancel-after-management-distributors-btn'
              style={`border: solid 1px ${dataColor.titleColor}; color: ${dataColor.titleColor};`}
            >
              切换
            </View>
          </Picker>
        </View>
        <View className='head'>
          <Image className='iconImg' src={RESOURCE_URL + "/resources/weapp/images/cashout-icon.png"} mode='aspectFill' />
          <View className='title'>可提金额</View>
          <View className='num total'><Text>￥</Text>{wallet.balance}</View>
        </View>
        <View className='btn-box tadpole'>
          <View className='btn'>
            {wallet.phone !== '' ?
              <Button
                disabled={!(wallet.balance >= wallet.minAmount && wallet.phone !== '')}
                onClick={this.cashOut.bind(this)}
                className={`${!wallet.acctNo && 'btn-style-disabled'} ${wallet.balance >= wallet.minAmount && wallet.phone !== '' ? 'btn-style' : 'btn-style-disabled'}`}
                style={`background-color: ${process.env.mainColor};`}
              >提现</Button>
              : <View
                onClick={this.disUse.bind(this)}
                className={`btn-style-disabled ${!wallet.acctNo && 'btn-disabled'}`}
                style={`background-color: ${process.env.mainColor};`}
              >提现</View>}
            <AtModal isOpened={showWithdraw} onClose={this.closedWithDraw.bind(this)} className='supplier-modal'>
              <AtModalHeader>温馨提示</AtModalHeader>
              <AtModalContent>
                收益将转入到{wallet.bankName}({wallet.acctNo})
              </AtModalContent>
              <AtModalAction>
                <View onClick={this.closedWithDraw.bind(this)} className='tixian-btn'>确定</View>
              </AtModalAction>
            </AtModal>
          </View>
        </View>
        <View className='tips-box'>
          {wallet.phone !== '' ?
            <Navigator url={'/distributor/wallet/supplierrecord?supplierId=' + formData.supplier_id}
              className='tips-item' hoverClass='none'
            >
              <AtIcon value='clock' size='16' color='#666'></AtIcon>
              <Text>交易记录</Text>
            </Navigator>
            : <View className='tips-item' hoverClass='none' onClick={this.disUse.bind(this)}>
              <AtIcon value='clock' size='16' color='#666'></AtIcon>
              <Text>交易记录</Text>
            </View>}

          {wallet.phone !== '' ? <Navigator
            url={"/distributor/wallet/ruleSupplier?min=" + wallet.minAmount + "&f=" + wallet.fee + "&max=" + wallet.maxAmount}
            className='tips-item' hoverClass='none'
          >
              <AtIcon value='alert-circle' size='16' color='#666'></AtIcon>
              <Text>规则说明</Text>
            </Navigator>
            : <View className='tips-item' hoverClass='none' onClick={this.disUse.bind(this)}>
              <AtIcon value='alert-circle' size='16' color='#666'></AtIcon>
              <Text>规则说明</Text>
            </View>}
        </View>
      </View>
    )
  }
}
